package com.netmera.mobile;

import v2.simpleUi.M_Caption;
import v2.simpleUi.M_Container;
import v2.simpleUi.M_EmailInput;
import v3.M_TextModifier;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.Toast;

public abstract class M_RegisterForm extends M_Container {
	private String nickname;
	private String email;
	protected String password;
	protected String aboutYourself;

	public M_RegisterForm() {

		add(new M_Caption("User Registration"));

		add(new M_TextModifier() {

			@Override
			public boolean save(String newValue) {
				nickname = newValue;
				return true;
			}

			@Override
			public String load() {
				return "";
			}

			@Override
			public String getVarName() {
				return "Nickname";
			}
		});
		add(new M_EmailInput() {

			@Override
			public boolean save(String validEmailAddress) {
				email = validEmailAddress;
				return true;
			}

			@Override
			public String load() {
				return "";
			}

			@Override
			public String getVarName() {
				return "Email";
			}
		});
		M_TextModifier pw = new M_TextModifier() {

			private Activity myContext;

			@Override
			public boolean save(String newValue) {
				if (newValue.length() < 4) {
					return false;
				}
				password = newValue;
				registerUser(myContext);
				return false;
			}

			@Override
			public View getView(Context context) {
				myContext = (Activity) context;
				return super.getView(context);
			}

			@Override
			public String load() {
				return "";
			}

			@Override
			public String getVarName() {
				return "Password";
			}
		};
		pw.isPasswordInput(true);
		add(pw);
		add(new M_TextModifier(true, true, false) {

			@Override
			public boolean save(String newText) {
				aboutYourself = newText;
				return true;
			}

			@Override
			public String load() {
				return "";
			}

			@Override
			public String getVarName() {
				return "About yourself";
			}
		});
	}

	protected void registerUser(final Activity a) {
		NetmeraUser u = new NetmeraUser();
		u.setEmail(email);
		u.setNickname(nickname);
		u.setPassword(password);
		u.registerInBackground(new NetmeraCallback<NetmeraUser>() {

			@Override
			public void callback(NetmeraUser u, NetmeraException e) {
				System.out.println("reister return");
				if (e != null) {
					e.printStackTrace();
					toast(a, "Registration error");
				} else {
					onUserLoggedIn(u, password, aboutYourself);
					a.finish();
				}
			}
		});
	}

	private void toast(Context a, String string) {
		Toast.makeText(a, string, Toast.LENGTH_LONG).show();
	}

	public abstract void onUserLoggedIn(NetmeraUser u, String pw,
			String aboutYourselfText);
}
